package com.sdy.hospitalguard.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.hospitalguard.biz.dto.MatchingPeopleDTO;
import com.sdy.hospitalguard.biz.model.*;
import com.sdy.hospitalguard.biz.service.*;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 人员匹配表 服务实现类
 * </p>
 *
 * @author zzq
 * @since 2020-05-15
 */
@Slf4j
@Service
public class MatchingPeopleServiceImpl extends BaseServiceImpl<MatchingPeople> implements MatchingPeopleService {

    @Autowired
    private AccessControlTerminalService accessControlTerminalService;
    @Autowired
    private EscortAssociatedService escortAssociatedService;
    @Autowired
    private PatientInformationService patientInformationService;
    @Autowired
    private VisitAppointmentService visitAppointmentService;
    @Autowired
    private TemporaryCardService temporaryCardService;
    @Autowired
    private InpatientAreaService inpatientAreaService;

    @Override
    public boolean add(MatchingPeople matchingPeople) throws BizException {
        // 手机端新增前判断sfz是否存在有效的临时通行证（2个表），有则把通行证变成无效
        QueryWrapper<TemporaryCard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("card_id", matchingPeople.getCardId());
        queryWrapper.ne("status", 2);
        TemporaryCard temporaryCard = temporaryCardService.getOne(queryWrapper);
        if (temporaryCard != null) {
            Integer building = inpatientAreaService.getById(temporaryCard.getAreaId()).getBuildingId();
            Integer userId = (1 << 30) | temporaryCard.getId();
            QueryWrapper<MatchingPeople> matchingPeopleQueryWrapper = new QueryWrapper<>();
            matchingPeopleQueryWrapper.eq("building", building.toString());
            matchingPeopleQueryWrapper.eq("user_id", userId);
            if (getOne(matchingPeopleQueryWrapper) != null ) {
                MatchingPeopleDTO matchingPeopleDTO = new MatchingPeopleDTO();
                matchingPeopleDTO.setUserId(userId);
                matchingPeopleDTO.setBuilding(building.toString());
                boolean success = deleteForType(matchingPeopleDTO);
                if (success) {
                    temporaryCardService.update(new UpdateWrapper<TemporaryCard>()
                            .eq("id", temporaryCard.getId()).set("status", 2));
                }
            }
        }
        QueryWrapper<MatchingPeople> wrapper = new QueryWrapper<>();
        wrapper.eq("building", matchingPeople.getBuilding());
        wrapper.eq("user_id", matchingPeople.getUserId());
        MatchingPeople m = getOne(wrapper);
        boolean success = true;
        if (m == null) {
            // 判断是否是临时卡新增
            if (matchingPeople.getUserId() > (1 << 30)) {
                // 删除系统原有的身份证数据，先查询后删除
                boolean error = accessControlTerminalService.selectPersonId(matchingPeople.getCardId(),
                        Integer.parseInt(matchingPeople.getBuilding()));
                if (!error) {
                    log.error("原身份证的人员查询异常，请检查查询接口，人员信息：{}", matchingPeople);
                    return false;
                }
            }
            success = accessControlTerminalService.addPerson(matchingPeople);
            if (success) {
                matchingPeople.setStatus(1);
                save(matchingPeople);
            }
        } else {
            if (!Objects.equals(m.getTimeTemplate(), matchingPeople.getTimeTemplate())) {
                if (StringUtil.isBlank(m.getTimeTemplate()) || StringUtil.isBlank(matchingPeople.getTimeTemplate())) {
                    matchingPeople.setTimeTemplate("");
                } else {
                    if (!m.getTimeTemplate().contains(matchingPeople.getTimeTemplate())){
                        String timeTemplateChange = m.getTimeTemplate() + "," + matchingPeople.getTimeTemplate();
                        // 剔除过期的时间戳段
                        timeTemplateChange = deleteDateForExpired(timeTemplateChange);
                        matchingPeople.setTimeTemplate(timeTemplateChange);
                    }
                }

            }
            success = accessControlTerminalService.addPerson(matchingPeople);
            if (success) {
                matchingPeople.setStatus(1);
                matchingPeople.setId(m.getId());
                update(matchingPeople, new UpdateWrapper<MatchingPeople>().eq("id", m.getId()));
            }
        }
        return success;
    }

    @Override
    public boolean delete(MatchingPeopleDTO matchingPeopleDTO) throws BizException {
        boolean success = true;
        QueryWrapper<MatchingPeople> wrapper = new QueryWrapper<>();
        wrapper.eq("building", matchingPeopleDTO.getBuilding());
        wrapper.eq("user_id", matchingPeopleDTO.getUserId());
        MatchingPeople m = getOne(wrapper);
        Assert.isNull(m, "当前人员信息查询不到，请重新确认需要删除的人员!");
        if (matchingPeopleDTO.getPatientId() == null) {
            // 判定为临时通行证
            success = accessControlTerminalService.deletePerson(m);
            if (success) {
                removeById(m.getId());
            }
            return success;
        }
        PatientInformation patientInformation = patientInformationService.getById(matchingPeopleDTO.getPatientId());
        String timeTemplate = matchingPeopleDTO.getTimeTemplate();
        if (patientInformation.getUserId().equals(matchingPeopleDTO.getUserId())) {
            // 是患者
            success = accessControlTerminalService.deletePerson(m);
            if (success) {
                removeById(m.getId());
            }
        } else if (StringUtil.isNotBlank(timeTemplate)) {
            // 是探视
            if (StringUtil.isBlank(m.getTimeTemplate())) {
                success = true;
            } else {
                String timeTemplateChange = m.getTimeTemplate().replace(timeTemplate, "");
                if (StringUtil.isBlank(timeTemplateChange)) {

                } else if (timeTemplateChange.substring(0, 1).equals(",")) {
                    timeTemplateChange = timeTemplateChange.substring(1);
                } else if (timeTemplateChange.substring(timeTemplateChange.length()-1).equals(",")) {
                    timeTemplateChange = timeTemplateChange.substring(0, timeTemplateChange.length()-1);
                } else if (timeTemplateChange.contains(",,")) {
                    timeTemplateChange = timeTemplateChange.replace(",,", ",");
                }
                if (StringUtil.isBlank(timeTemplateChange)) {
                    success = accessControlTerminalService.deletePerson(m);
                    if (success) {
                        removeById(m.getId());
                    }
                } else {
                    // 剔除过期的时间戳段
                    timeTemplateChange = deleteDateForExpired(timeTemplateChange);
                    long lastChange = System.currentTimeMillis()/1000;
                    success = accessControlTerminalService.addPerson(m
                            .setTimeTemplate(timeTemplateChange)
                            .setLastChange(String.valueOf(lastChange)));
                    if (success) {
                        update(new UpdateWrapper<MatchingPeople>().eq("id", m.getId())
                                .set("time_template", timeTemplateChange)
                                .set("last_change", String.valueOf(lastChange)));
                    }
                }
            }
        } else {
            /*QueryWrapper<EscortAssociated> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", matchingPeopleDTO.getUserId());
            queryWrapper.eq("patient_id", matchingPeopleDTO.getPatientId());
            queryWrapper.eq("attendant_state", 0);
            queryWrapper.eq("flow_state", 0);
            EscortAssociated escortAssociated = escortAssociatedService.getOne(queryWrapper);
            Assert.isNull(escortAssociated, "数据传输不规范!");*/
            // 查询此陪护所有未过期的探视记录
            QueryWrapper<VisitAppointment> visitAppointmentQueryWrapper = new QueryWrapper<>();
            visitAppointmentQueryWrapper.eq("user_id", matchingPeopleDTO.getUserId());
            visitAppointmentQueryWrapper.eq("appointment_state", 0);
            visitAppointmentQueryWrapper.ne("visit_state", 3);
            visitAppointmentQueryWrapper.ne("status", 1);
            visitAppointmentQueryWrapper.ge("visit_end_time", new Date());
            // 注释的应该没用了
            //visitAppointmentQueryWrapper.gt("visit_start_time", new Date());
            List<VisitAppointment> visitAppointmentList = visitAppointmentService.list(visitAppointmentQueryWrapper);
            Integer visitAppointmentListSize = visitAppointmentList.size();
            if (visitAppointmentListSize > 0) {
                String time = "";
                for (int i=0; i < visitAppointmentListSize; i++) {
                    if (Integer.parseInt(patientInformationService.getById(visitAppointmentList.get(i).getPatientId()).getFloorId()) ==
                            Integer.parseInt(patientInformation.getFloorId())) {
                        time = time + visitAppointmentList.get(i).getVisitStartTime().getTime()/1000
                                + "-" + visitAppointmentList.get(i).getVisitEndTime().getTime()/1000 + ",";
                    }
                }
                if (StringUtil.isBlank(time)) {
                    success = accessControlTerminalService.deletePerson(m);
                    if (success) {
                        removeById(m.getId());
                    }
                } else {
                    time = time.substring(0, time.length() - 1);
                    long lastChange = System.currentTimeMillis()/1000;
                    success = accessControlTerminalService.addPerson(m
                            .setTimeTemplate(time)
                            .setLastChange(String.valueOf(lastChange)));
                    if (success) {
                        update(new UpdateWrapper<MatchingPeople>().eq("id", m.getId())
                                .set("time_template", time)
                                .set("last_change", String.valueOf(lastChange)));
                    }
                }
            } else {
                success = accessControlTerminalService.deletePerson(m);
                if (success) {
                    removeById(m.getId());
                }
            }
        }
        return success;
    }

    @Override
    public boolean deleteForType(MatchingPeopleDTO matchingPeopleDTO) throws BizException {
        boolean success = true;
        QueryWrapper<MatchingPeople> wrapper = new QueryWrapper<>();
        wrapper.eq("building", matchingPeopleDTO.getBuilding());
        wrapper.eq("user_id", matchingPeopleDTO.getUserId());
        MatchingPeople m = getOne(wrapper);
        Assert.isNull(m, "当前人员信息查询不到，请重新确认需要删除的人员!");
        success = accessControlTerminalService.deletePerson(m, 1);
        if (success) {
            removeById(m.getId());
        }
        return success;
    }

    /**
     * 剔除过期的时间戳段
     * @param timeTemplateChange
     * @return
     */
    public String deleteDateForExpired(String timeTemplateChange) {
        long dateTime = System.currentTimeMillis()/1000;
        String[] timeTemplateChangeArray = timeTemplateChange.split(",");
        Integer length = timeTemplateChangeArray.length;
        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0; i<length; i++) {
            if(dateTime <= Long.parseLong(timeTemplateChangeArray[i].split("-")[1])) {
                stringBuffer.append(timeTemplateChangeArray[i] + ",");
            }
        }
        String s = stringBuffer.toString();
        if (StringUtil.isBlank(s)) {
            return "";
        }
        return s.substring(0, s.length()-1);
    }
}
